<template>
  <div class="login">
    <el-form
      label-width="80px"
      :model="loginForm"
      :rules="rules"
      ref="loginFormRef"
    >
      <el-form-item label="用户名" prop="loginName">
        <el-input v-model="loginForm.loginName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input
          v-model="loginForm.code"
          style="width: 160px; left: -32px; top: -19px"
        ></el-input>
        <img :src="changeImage" alt="" @click="changeImg" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button type="info">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from "@/api/user";
export default {
  data() {
    return {
      loginForm: {
        loginName: "admin",
        password: "admin",
        code: "",
        clientToken: "",
        loginType: "0",
      },
      rules: {
        loginName: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 5, max: 16, message: "用户名长度在5-16之间", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 5, max: 16, message: "密码长度在5-16之间", trigger: "blur" },
        ],
        code: [{ required: true, message: "密码不能为空", trigger: "blur" }],
      },
      random: Math.random(),
      changeImage: "",
    };
  },
  methods: {
    async onSubmit() {
      await this.$refs.loginFormRef.validate();
      this.loginForm.clientToken = this.random;
      const {
        data: { token },
      } = await login(this.loginForm);
      // console.log(token);
      this.$store.commit("user/setToken", token);

      // setName(this.loginForm.loginName);
      this.$router.push("/layout");
    },
    changeImg() {
      this.random = Math.random();
      this.handleClickImge();
    },
    handleClickImge() {
      this.changeImage =
        "http://likede2-admin.itheima.net/likede/api/user-service/user/imageCode/" +
        this.random;
    },
  },
  mounted() {
    this.handleClickImge();
  },
};
</script>

<style lang="scss" scoped>
.login {
  width: 400px;
  height: 350px;
  //background-color: blue;
  margin: 100px auto;
  .el-form-item {
    text-align: right;
  }
}
</style>
